<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="升级包名称" prop="name">
        <el-input
          v-model="queryParams.name"
          size="mini"
          placeholder="请输入升级包名称"
          clearable
          @clear="handleQuery"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="升级包版本" prop="version" label-width="100px">
        <el-input
          size="mini"
          v-model="queryParams.version"
          placeholder="请输入版本号"
          clearable
          @clear="handleQuery"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="版本类型"
          clearable
          @clear="handleQuery"
          @keyup.enter.native="handleQuery"
          style="width: 140px"
        >
          <el-option
            v-for="item in dict.type.fireware_version_type"
            :key="parseInt(item.value)"
            :label="item.label"
            :value="parseInt(item.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['device:firmwareInfo:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="firmwareInfoList">
      <el-table-column label="序号" type="index" fixed></el-table-column>
      <el-table-column label="升级包名称" align="center" prop="name" width="150"/>
      <el-table-column label="升级包版本" align="center" prop="versionName" width="100"/>
      <el-table-column label="升级包类型" align="center" prop="type" width="100" :formatter="typeFormat" />
      <el-table-column label="下载地址" align="center" prop="fileUrl" width="300" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <i class="el-icon-document-copy" v-clipboard:copy="scope.row.fileUrl" v-clipboard:success="copyText" style="margin-right: 5px;cursor: pointer;"></i>
          {{ scope.row.fileUrl }}
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center" prop="remark" width="300"/>
      <el-table-column label="上传时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['device:manage:edit']"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['device:manage:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="200px">
        <el-row>
          <el-col :span="11">
            <el-form-item label="版本名称:" prop="name" label-width="110px">
              <el-input v-model="form.name" placeholder="请输入应用名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18">
            <el-col :span="16">
              <el-form-item label="升级文件:" prop="fileUrl" label-width="120px">
                <div class="file_img" v-if="form.fileUrl != null && form.fileUrl != '' ">
                  <span>
                   <el-button type="info" icon="el-icon-download" @click="downloadFirmware">下载包</el-button>
                  </span>
                </div>
                <div style="margin-top:20px">
                  <el-upload
                    class="upload-template"
                    ref="upload"
                    drag
                    :action="uploadUrl"
                    :limit="1"
                    :show-file-list="false"
                    :before-upload="handleBeforeUpload"
                    :on-success="handleUploadSuccess"
                    :on-error="handleUploadError"
                    :on-progress="uploadFirmwareProcess"
                    :headers="headers">
                    <i class="el-icon-upload"></i>
                    <!-- 进度条 -->
                    <el-progress v-if="progressFlag" :percentage="loadProgress"></el-progress>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <div class="el-upload__tip" slot="tip" style="margin-top: -20px">上传图片只能固件  !</div>
                  </el-upload>
                </div>
              </el-form-item>
            </el-col>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span=11>
            <el-form-item label="版本号:" prop="version" label-width="110px">
              <el-input placeholder="请输入版本" v-model="form.version">
                <template slot="prepend">v</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span=11>
            <el-form-item label="版本类型:" prop="type" label-width="110px">
              <el-select
                v-model="form.type"
                placeholder="版本类型"
                clearable
                @clear="handleQuery"
                @keyup.enter.native="handleQuery"
                style="width: 140px"
              >
                <el-option
                  v-for="item in dict.type.fireware_version_type"
                  :key="parseInt(item.value)"
                  :label="item.label"
                  :value="parseInt(item.value)"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span=20>
            <el-form-item label="备注:" prop="remark" label-width="110px">
              <el-input
                type="textarea"
                :rows="4"
                placeholder="请输入备注"
                v-model="form.remark">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="margin-top: 10px">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {selectFirmwareInfoList,delFirmwareInfo,selectFirmwareInfo,updateFirmwareInfo,insertFirmwareInfo} from "@/api/platform/device/firmware/fireware";
import {getToken} from "@/utils/auth";

export default {
  name: "FirmwareInfo",
  dicts: ['fireware_version_type'],
  data() {
    return {
      loadProgress: 0, // 动态显示进度条
      progressFlag: false, // 关闭进度条
      uploadUrl: process.env.VUE_APP_BASE_API + "/system/file/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken()
      },
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      firmwareInfoList: [],
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示添加修改弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "应用名称不能为空", trigger: "blur" }
        ],
        version: [
          { required: true, message: "版本不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "类型不能为空", trigger: "blur" }
        ],
        fileUrl:[
          { required: true, message: "升级文件不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询模板列表 */
    getList() {
      this.loading = true;
      selectFirmwareInfoList(this.queryParams).then(response => {
        this.firmwareInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      })
    },
    typeFormat(row, index) {
      if (row.type === 0) {
        return "固件版本";
      } else if(row.type === 1){
        return "软件版本";
      }
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      /*
      const type = ["audio/mpeg", "audio/wav"];
      const isJPG = type.includes(file.type);
      // 检验文件格式
      if (!isJPG) {
        this.$message.error(`文件格式错误!`);
        return false;
      }

       */
      const isLt = ((file.size / 1024 / 1024) < 20);
      if (!isLt) {
        this.$message.error(`上传文件大小不能超过 20 MB!`);
        return false;
      }
      return true;
    },
    uploadFirmwareProcess(event, file, fileList) {
      this.progressFlag = true; // 显示进度条
      this.loadProgress = parseInt(event.percent); // 动态获取文件上传进度
      if (this.loadProgress >= 100) {
        this.loadProgress = 100
        setTimeout( () => {this.progressFlag = false}, 1000) // 一秒后关闭进度条
      }
    },
    handleUploadSuccess(res, file) {
      // 如果上传成功
      if (res.code == 200) {
        this.form.fileUid = res.data.uid;
        this.form.fileUrl = res.data.url;
        this.$message.success("上传成功");
        this.$refs.upload.clearFiles()
      } else {
        this.$message.error("上传失败");
      }
    },
    handleUploadError() {
      this.$message.error("上传失败");
    },
    copyText(){
      this.$message.success("复制成功")
    },

    downloadFirmware(){
      window.open(this.form.fileUrl)
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增包版本信息";
    },
    //修改按钮
    handleUpdate(row) {
      this.reset();
      this.open = true;
      this.title = "修改包版本信息";
      selectFirmwareInfo(row.uid).then(response =>{
        this.form = response.data;
      })
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },

    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.uid == undefined) {
            let data = this.form
            const message = "<div>确定要新增设备信息？</div>"
            this.$modal.confirm(message).then(function() {
              return insertFirmwareInfo(data);
            }).then(() => {
              this.reset()
              this.$modal.msgSuccess("修改成功");
              this.open=false;
              this.getList();
            })
          }else{
            let data = this.form;
            //提示
            const message = "<div>确定要修改应用信息？</div>"
            this.$modal.confirm(message).then(function() {
              return updateFirmwareInfo(data);
            }).then(() => {
              this.reset()
              this.$modal.msgSuccess("修改成功");
              this.open=false;
              this.getList();
            })
          }
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      let data = {
      };
      data.uid = row.uid;
      //提示
      const message = "<div>确定要删除应用: <span>" + row.name + " ?</span></div>"+
        "<span style='margin-top: 20px'>应用ID:</span> &nbsp;&nbsp;&nbsp;" + row.uid
      this.$modal.confirm(message).then(function() {
        return delFirmwareInfo(data);
      }).then(() => {
        this.$modal.msgSuccess("删除成功");
        this.getList()
      })
    },
  }
};
</script>
<style scoped>
/deep/ .el-textarea__inner {
  resize: none;
}
</style>
